<template>
    <div>
        <el-table :data="tableData" stripe style="width: 100%" @row-click="onRowClick" v-loading="loading" element-loading-text="Logining..." ref="orderTable" fit>
            <el-table-column type="index" width="50" />
            <el-table-column prop="ticketId" label="Ticket ID" />
            <el-table-column prop="orderId" label="OrderId" />
            <el-table-column prop="deviceId" label="IMEI" />
            <el-table-column prop="deviceName" label="Device Name" />
            <el-table-column prop="orderType" label="Order Type" />
            <el-table-column prop="account" label="Owner" />
            <el-table-column prop="phonenumber" label="Phone number" />
            <el-table-column prop="countryCode" label="Country Code" >
                <template #default="scope">
                    {{ getCountry(scope.row.countryCode) }}
                </template>
            </el-table-column>
            <el-table-column prop="recordType" label="number type" />
            <el-table-column prop="created" label="Create Time" sortable>
                <template #default="scope">
                    {{ new Date(scope.row.created * 1000).toISOString() }}
                </template>
            </el-table-column>
            <el-table-column prop="expired" label="Expired Time" sortable>
                <template #default="scope">
                    {{ new Date(scope.row.expired * 1000).toISOString() }}
                </template>
            </el-table-column>
            <el-table-column 
                prop="status" 
                label="Status" 
                width="200"
                sortable
                >
                <template #default="scope">
                    <el-select
                    v-model="scope.row.status"
                    placeholder="Select"
                    size="default"
                    style="width: 180px"
                    @change="onStatusChange($event, scope)"
                    >
                        <el-option label="active" value="active"/>
                        <el-option label="processing" value="processing"/>
                        <el-option label="finished" value="finished"/>
                    </el-select>  
                </template>
            </el-table-column>
            <el-table-column fiexd="right" label="Operation">
                <template #default="scope">
                    <el-button size="small" @click.stop="onDeleteClick($event, scope)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { api_del_order, api_get_all_orders, api_update_order, codeToCountryMap } from '../api/apis';
import { useGlobalStore } from '../store';
import { useRouter } from 'vue-router';
import { ElMessage, ElTable } from 'element-plus';

const router = useRouter();

const orderTable = ref<InstanceType<typeof ElTable>>()

type OrderInfo = {
    ticketId: string,
    orderId: string,
    deviceId: string,
    deviceName: string,
    orderType: string,
    account: string,
    phonenumber: string,
    countryCode: string,
    recordType: string,
    created: number,
    expired: number
}

const store = useGlobalStore();
const loading = ref(false);
const tableData = ref<OrderInfo[]>([]);

const onDeleteClick = async (e: any, scope: any) => {
    console.log("onDeleteClick", e, scope.row);
    try {
        const ret = await api_del_order(scope.row.ticketId);
        console.log("api_del_order", ret);

        if (ret.status == 200) {
            if (ret.data.errCode == 0) {
                ElMessage({
                    message: 'Delete success',
                    type: 'success',
                });

                let index = tableData.value.findIndex((item) => item.ticketId == scope.row.ticketId);
                if (index != -1) {
                    tableData.value.splice(index, 1);
                    store.orderList.splice(index, 1);
                }
            }
        }
    }catch (err: any) {
        console.log("exception happened. error: ", err);
        if (err.response.status == 401) {
            router.replace({name: "login"});
        }
    }
}

const onStatusChange = async (e: any, scope: any) => {
    console.log("onStatusChange", e, scope);
    try {
        const ret = await api_update_order(scope.row.ticketId, scope.row.status);
        console.log("api_update_order", ret);

        if (ret.status == 200) {
            if (ret.data.errCode == 0) {
                ElMessage({
                    message: 'Update success',
                    type: 'success',
                });
            }
        }
    }catch (err: any) {
        console.log("exception happened. error: ", err);
        if (err.response.status == 401) {
            router.replace({name: "login"});
        }
    }
}

onMounted(() => {

    (async () => {
        loading.value = true;
        console.log('page onUpdated');
        
        try {
            const ret = await api_get_all_orders();
            console.log('api_get_all_orders', ret);

            if (ret.status == 200) {
                if (ret.data.errCode == 0) {
                    const datas = ret.data.data;
                    store.orderList = [];
                    tableData.value = datas.map((item: any) => {
                        console.log("item", item);
                        store.orderList.push(item);
                        return item;
                    })

                    tableData.value.sort((a, b) => (a.created - b.created));
                }
            }
        }catch (err: any) {
            console.log("exception happened. error: ", err);
            if (err.response.status == 401) {
                router.replace({name: "login"});
            }
        }finally {
            loading.value = false;
        }
    })(); 
})

const onRowClick = (row: any) => {
    orderTable.value!.setCurrentRow(row);
    console.log("onRowClick", row.orderId);
    router.push('/console/detail/' + row.orderId)
}

const getCountry = (countryCode: string): string => {
    if (codeToCountryMap.has(countryCode)) {
        return `${codeToCountryMap.get(countryCode)} (${countryCode})`;
    }else {
        return countryCode;
    }
}

</script>

<style scoped>

</style>